//
//  MBRecordFreedomController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/26.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBRecordFreedomController.h"
#import "MBPlayShowController.h"
#import "MBSendShowController.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayerVIew.h"
typedef enum {
    IdentityType_record = 0,
    IdentityType_pauseRecord,
    IdentityType_continueRecord,
    
}IdentityType;

#define RECORD_MUSIC_PATH(fileName) ([MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",fileName]])
#define MUSIC_PRIVATE_NAME  (@"AAA")
@interface MBRecordFreedomController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,AVAudioRecorderDelegate,AVAudioPlayerDelegate>
{
    AVAudioSession              *_audioSession;
    AVAudioRecorder             *_audioRecorder;
    AVAudioPlayer               *_audioPlayer;
    NSTimer                     *_recordTimer;
    NSInteger                   secondIndex;   //时间
    UIButton                    *_contentBt; //播放按钮
    UIButton                    *_recordAndContinuBt; //录制或继续按钮
    PlayerView                  *playerView;
}
@property (nonatomic, strong) UIButton *reRecord;//重录
@property (nonatomic, strong) UIButton *promulgate;//发布
@property (nonatomic, strong) UIButton *sendPictureBtn;
@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic,assign)IdentityType    identityType;

@property (nonatomic,strong) NSString   *titleString;
@property (nonatomic, strong) UILabel *recordLb;
@property (nonatomic, strong) UISlider *sliderBtn;
@end


@implementation MBRecordFreedomController

//判断麦克风权限
- (void)setRecordPermission
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
        
        switch (permissionStatus) {
            case AVAudioSessionRecordPermissionUndetermined:{
                NSLog(@"第一次调用，是否允许麦克风弹框");
                [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                    // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
                    if (granted) {
                        // Microphone enabled code
                    }
                    else {
                        // Microphone disabled code
                    }
                }];
                break;
            }
            case AVAudioSessionRecordPermissionDenied:
                // direct to settings...
                NSLog(@"已经拒绝麦克风弹框");
                [ErrorMessage showErrorMessage:@"请到设置中打开麦克风权限" inView:self.view];
                break;
            case AVAudioSessionRecordPermissionGranted:
                NSLog(@"已经允许麦克风弹框");
                // mic access ok...
                break;
            default:
                // this should not happen.. maybe throw an exception.
                break;
        }
        if(permissionStatus == AVAudioSessionRecordPermissionUndetermined) return;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    secondIndex = 0;
    
    if ([UserManager standerDefult].mainPlayer) {
        [[UserManager standerDefult].mainPlayer pause];
    }
   
    [self setRecorderURL:[NSURL fileURLWithPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)] withSettings:nil];
    
    if (ISIPAD) {
        [self creatUIForIpad];
    }
    else{
        [self setupUI];
    }
    
    [self setBackItem];
    [self setRecordPermission];
}

#pragma mark---IPad UI
-(void)creatUIForIpad{
    playerView=[[PlayerView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:playerView];
    
    //重录
    [playerView.RerecodBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    //录制
     [playerView.continueBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    //发布
     [playerView.publishBtn addTarget:self action:@selector(sendBtn) forControlEvents:UIControlEventTouchUpInside];
    //播放
     [playerView.playBtn addTarget:self action:@selector(onSelectForPlayerAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //暂无歌词
    UIImageView * loseImg=[[UIImageView alloc]initWithFrame:CGRectMake(playerView.bigImg.right+489*PERCEN, 532*PERCEN, 120*PERCEN, 120*PERCEN)];
    loseImg.image=[UIImage imageNamed:@"zanwugeci"];
    [playerView addSubview:loseImg];
    
    UILabel * loseLabel=[[UILabel alloc]initWithFrame:CGRectMake(playerView.bigImg.right+472*PERCEN, loseImg.bottom+80*PERCEN, 160*PERCEN, 40*PERCEN)];
    loseLabel.textColor=UIColorFromHex(0xffffff);
    loseLabel.font=[UIFont systemFontOfSize:40*PERCEN];
    loseLabel.text=@"暂无歌词";
    [playerView addSubview:loseLabel];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

     [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    if (_recordTimer) {
        [_recordTimer invalidate];
        _recordTimer = nil;
    }
}

- (void)setupUI {

    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height-400*PERCEN)];
    bgImageView.image = [UIImage imageNamed:@"qzx_player_bg"];
//    bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:bgImageView];
    self.bgImageView = bgImageView;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 934*PERCEN_HEIGHT)];
    bgView.backgroundColor = [UIColor clearColor];
//    bgView.alpha = 0.2;
    [self.view addSubview:bgView];
    
//    UIButton *sendPictureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    sendPictureBtn.frame = CGRectMake(0, 158*PERCEN, SCREEN_WIDTH, bgView.height-158*PERCEN);
////    [sendPictureBtn setBackgroundImage:[UIImage imageNamed:@"banner1"] forState:UIControlStateNormal];
////    sendPictureBtn.alpha = 0.2;
//    //上传图片按钮
//    [sendPictureBtn addTarget:self action:@selector(sendPicture) forControlEvents:UIControlEventTouchUpInside];
//
//    [self.view addSubview:sendPictureBtn];
//    self.sendPictureBtn = sendPictureBtn;
    
    UIView *recordView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-400*PERCEN, SCREEN_WIDTH, 400*PERCEN)];
    recordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:recordView];
    
    UISlider *sliderBtn = [[UISlider alloc] initWithFrame:CGRectMake(0, 20*PERCEN, SCREEN_WIDTH, 10*PERCEN)];
    sliderBtn.minimumValue = 0;
    sliderBtn.maximumValue = 1;
    sliderBtn.value = 0;
    sliderBtn.minimumTrackTintColor = TINK_BG_COLOR;
    sliderBtn.maximumTrackTintColor = [UIColor colorWithRed:193/255. green:193/255. blue:193/255. alpha:1.];
    [sliderBtn setThumbImage:[UIImage imageNamed:@"jiedian"] forState:UIControlStateNormal];
    [sliderBtn setThumbImage:[UIImage imageNamed:@"jiedian"] forState:UIControlStateHighlighted];
    [recordView addSubview:sliderBtn];
    self.sliderBtn = sliderBtn;
    
    UILabel *recordLb = [[UILabel alloc] initWithFrame:CGRectMake( (SCREEN_WIDTH-400*PERCEN)/2,sliderBtn.bottom+10*PERCEN, 400*PERCEN, 20*PERCEN)];
    recordLb.text = @"准备录制00:00/15:00";
    recordLb.font = [UIFont systemFontOfSize:12.0f];
    recordLb.textColor = UIColorFromHex(0x999999);
    recordLb.textAlignment = NSTextAlignmentCenter;
    [recordView addSubview:recordLb];
    self.recordLb = recordLb;
    
    UIButton *recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [UIImage imageNamed:@"jixuluyin"];
    
    recordBtn.frame = CGRectMake((SCREEN_WIDTH-img.size.width)/2, recordView.height-img.size.height-90*PERCEN, img.size.width, img.size.height);
    [recordBtn setTitle:@"录音" forState:UIControlStateNormal];

    [recordBtn setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
    recordBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [recordBtn setBackgroundImage:img forState:UIControlStateNormal];
    [recordBtn addTarget:self action:@selector(clickBtn: ) forControlEvents:UIControlEventTouchUpInside];
    [recordView addSubview:recordBtn];
    _recordAndContinuBt = recordBtn;
    
    //重录
    UIImage *Reimg = [UIImage imageNamed:@"chonglu"];
    UIButton *reRecord = [UIButton buttonWithType:UIButtonTypeCustom];
    reRecord.frame = CGRectMake(recordBtn.left-50*PERCEN-Reimg.size.width, recordBtn.centery-Reimg.size.height/2, Reimg.size.width, Reimg.size.height);
    [reRecord setTitle:@"重录" forState:UIControlStateNormal];
    self.reRecord = reRecord;
    [reRecord setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
    reRecord.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [reRecord setBackgroundImage:img forState:UIControlStateNormal];
    [reRecord addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [recordView addSubview:reRecord];
    reRecord.hidden  = YES;
    //发布
    UIButton *sendRecord = [UIButton buttonWithType:UIButtonTypeCustom];
    sendRecord.frame = CGRectMake(recordBtn.right+50*PERCEN,  recordBtn.centery-Reimg.size.height/2,Reimg.size.width, Reimg.size.height);
    [sendRecord setTitle:@"发布" forState:UIControlStateNormal];
    self.promulgate = sendRecord;
    
    [sendRecord setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
    sendRecord.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    
    [sendRecord setBackgroundImage:img forState:UIControlStateNormal];
    [sendRecord addTarget:self action:@selector(sendBtn) forControlEvents:UIControlEventTouchUpInside];
    [recordView addSubview:sendRecord];
    sendRecord.hidden = YES;
    //播放按钮
        UIImage *imgPlay = [UIImage imageNamed:@"bofang"];
        _contentBt = [UIButton buttonWithType:UIButtonTypeCustom];
        _contentBt.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.25];
        _contentBt.frame = CGRectMake(0, bgView.top, bgView.width, 934*PERCEN_HEIGHT);
        [_contentBt setImage:imgPlay forState:UIControlStateNormal];
        [_contentBt setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateSelected];

        [_contentBt addTarget:self action:@selector(onSelectForPlayerAction:) forControlEvents:UIControlEventTouchUpInside];
        _contentBt.hidden = YES;
        [self.view addSubview:_contentBt];

}

#pragma mark - 播放
- (void)onSelectForPlayerAction:(UIButton *)bt
{
    bt.selected = !bt.selected;
    
    if (_audioSession) {
        [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [_audioSession setActive:NO error:nil];
    }
    NSString *filePath = RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME);
    
    if (!_audioPlayer) {
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];
        _audioPlayer.delegate = self;
    }
    
    if (bt.selected) {
        [_audioPlayer prepareToPlay];
        [_audioPlayer play];
        [_sliderBtn setValue:0 animated:YES];
        
        int second = (int)_audioPlayer.currentTime / 60;
        int minter = (int)_audioPlayer.currentTime % 60;
        if (ISIPAD) {
            playerView.currentLabel.text=[NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
        }else{
        _recordLb.text = [NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
        }
        if (!_recordTimer) {
            _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        }
    } else {
        [_audioPlayer pause];
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
    }
    
}

//弹出相片选择框
- (void)sendPicture
{
    if (IOS(8.0)) {
        UIAlertController *alertContr = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypeCamera];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
        }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertContr addAction:action1];
        [alertContr addAction:action2];
        [alertContr addAction:action3];
        [action1 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action2 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action3 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [self.navigationController presentViewController:alertContr animated:YES completion:NULL];
    } else {
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开照相机" otherButtonTitles:@"从手机相册获取", nil];
        [sheet showInView:self.view];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self onChooseType:UIImagePickerControllerSourceTypeCamera];
    }
    else if (buttonIndex == 1) {
        [self onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    else if (buttonIndex == 2) {
        
    }
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    for (UIView *view in actionSheet.subviews) {
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            label.textColor = [UIColor blackColor];
        }
    }
}

#pragma mark - 相片
- (void)onChooseType:(UIImagePickerControllerSourceType)sourceType
{
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            NSLog(@"该手机不能拍照");
            return;
        }
    }
    
    UIImagePickerController *pickerCtrl = [[UIImagePickerController alloc]init];
    pickerCtrl.sourceType = sourceType;
    pickerCtrl.delegate = self;
    pickerCtrl.allowsEditing = YES;
    [self.navigationController presentViewController:pickerCtrl animated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (info.count > 0) {
        UIImage *originImg = [info objectForKey:UIImagePickerControllerEditedImage];
        self.bgImageView.image =[UIImage imageWithData:[self onGetPictureForIMG:originImg]];
        
        [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (NSData *)onGetPictureForIMG:(UIImage *)img
{
    CGRect rect = CGRectMake(0, 0, 300, 300);
    UIGraphicsBeginImageContext(rect.size);
    [img drawInRect:rect];
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(newImg);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
}

//点击录制按钮
- (void)clickBtn:(UIButton *)sender {
    _identityType++;
    if (self.reRecord == sender) {
        //是重按按钮
        _identityType = 0;
    }
    if (playerView.RerecodBtn == sender) {
        _identityType = 0;
    }
    if (ISIPAD) {
        playerView.RerecodBtn.hidden=YES;
        playerView.publishBtn.hidden= YES;
    }else{
    self.reRecord.hidden = YES;
    self.promulgate.hidden = YES;
    }
    if (_identityType == 3) {
        _identityType = 1;
    }
    
    if (_identityType == IdentityType_record) {
        //起始
        [sender setTitle:@"录音" forState:UIControlStateNormal];
        if (!ISIPAD) {
            
            [sender setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
            [sender setBackgroundImage:[UIImage imageNamed:@"jixuluyin"] forState:UIControlStateNormal];
            
        }else {
            [sender setTitle:@"重录" forState:UIControlStateNormal];
        }
        
             //重录 数据清空
          secondIndex = 0;
        if (ISIPAD) {
            playerView.currentLabel.text=@"准备录制00:00/15:00";
            [playerView.progressSlider setValue:(1. * secondIndex / 900) animated:YES];
        }else{
        _recordLb.text = @"准备录制00:00/15:00";
      
        [_sliderBtn setValue:(1. * secondIndex / 900) animated:YES];
        }
        [_audioRecorder stop];
        NSFileManager *fileManager = [[NSFileManager alloc]init];
        if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
            [fileManager removeItemAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME) error:nil];
        }
        [self setRecorderURL:[NSURL fileURLWithPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)] withSettings:nil];
        
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
        _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        
        _contentBt.hidden = YES;
    }
    else if (_identityType == IdentityType_pauseRecord) {
        //开始录音
        [sender setTitle:@"暂停录音" forState:UIControlStateNormal];
        if (!ISIPAD) {
            [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [sender setBackgroundImage:[UIImage imageNamed:@"zantingluyin"] forState:UIControlStateNormal];
        }
     
        //        _recordShowTitleLb.text = @"正在录制00:00/15:00";
        if (_audioPlayer) {
            [_audioSession setActive:NO error:nil];
            [_audioPlayer stop];
            [_audioPlayer prepareToPlay];
            _audioPlayer = nil;
        }
        if (_audioSession) {
            [_audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
            [_audioSession setActive:YES error:nil];
        }
        [_audioRecorder record];
        [_sliderBtn setValue:(1. * secondIndex / 900) animated:YES];
        if (!_recordTimer) {
            _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        }
        if (ISIPAD) {
            playerView.playBtn.hidden=YES;
            playerView.playBtn.selected=NO;
        }else{
        _contentBt.hidden = YES;
        _contentBt.selected = NO;
        }
    }
    else if (_identityType ==IdentityType_continueRecord) {
        //暂停了
        [sender setTitle:@"继续录音" forState:UIControlStateNormal];
        if (!ISIPAD) {
            
            [sender setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
            [sender setBackgroundImage:[UIImage imageNamed:@"jixuluyin"] forState:UIControlStateNormal];
            

        }
        
               int second = (int)secondIndex / 60;
        int minter = (int)secondIndex % 60;
        if (ISIPAD) {
            playerView.currentLabel.text= [NSString stringWithFormat:@"准备录制%02d:%02d/15:00",second,minter];
        }else {
        _recordLb.text = [NSString stringWithFormat:@"准备录制%02d:%02d/15:00",second,minter];
        }
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
        
        [_audioRecorder pause];
        if (ISIPAD) {
            playerView.RerecodBtn.hidden=NO;
            playerView.publishBtn.hidden=NO;
            playerView.playBtn.hidden=NO;
        }else{
        self.reRecord.hidden = NO;
        self.promulgate.hidden = NO;
        _contentBt.hidden = NO;
        }
    }
    
}

- (void)onRecordMusic
{
    if (_identityType == IdentityType_pauseRecord) {
        if (secondIndex >= 15*60) {
            //到了15分钟结束
            if (_recordTimer) {
                [_recordTimer invalidate];
                _recordTimer = nil;
            }
            [ErrorMessage showErrorMessage:@"最多录制15分钟" inView:self.view];
            [self clickBtn:_recordAndContinuBt];
            return;
        }
        ++secondIndex;
        int second = (int)secondIndex / 60;
        int minter = (int)secondIndex % 60;
        
        if (ISIPAD) {
            playerView.currentLabel.text= [NSString stringWithFormat:@"正在录制%02d:%02d/15:00",second,minter];
            [playerView.progressSlider setValue:(1. * secondIndex / 900) animated:YES];
        }else{
        _recordLb.text = [NSString stringWithFormat:@"正在录制%02d:%02d/15:00",second,minter];
        
        [_sliderBtn setValue:(1. * secondIndex / 900) animated:YES];
        }
    }
    else if (_identityType == IdentityType_continueRecord) {
        float value =  _audioPlayer.currentTime/900.0;
        int second = (int)_audioPlayer.currentTime / 60;
        int minter = (int)_audioPlayer.currentTime % 60;
       
        if (ISIPAD) {
            [playerView.progressSlider setValue:value animated:YES];
            playerView.currentLabel.text = [NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
            
        }else{
            [_sliderBtn setValue:value animated:YES];
             _recordLb.text = [NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
        }
        
        if (second * 60 + minter >= secondIndex) {
            //播放超过录制时间十，暂停
            if (_recordTimer) {
                [_recordTimer invalidate];
                _recordTimer = nil;
            }
            [self onSelectForPlayerAction:_contentBt];
            return;
        }

    }
    
}

- (void)setRecorderURL:(NSURL *)urlPath withSettings:(NSDictionary *)settings
{
    
    if (!_audioSession) {
        _audioSession = [AVAudioSession sharedInstance];
    }
    [_audioSession setActive:YES error:nil];
    /*
     当你在只录音的时候可以讲category设置为AVAudioSessionCategoryRecord
     需要录音并播放的时候设置AVAudioSessionCategoryPlayAndRecord；
     需要播放的时候设置AVAudioSessionCategoryPlayback。
     */
    [_audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    //设置播放器为扬声器模式
    [_audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    
    
    if (!settings) {
        NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc]initWithCapacity:10];
        [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
        [recordSettings setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];//采样率
        [recordSettings setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];//通道的数目,1单声道,2立体声
        [recordSettings setValue:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];//解码率
        [recordSettings setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];//采样位 8/16/24/32
        [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
        [recordSettings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
        [recordSettings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
        
        settings = recordSettings;
    }
    
    NSError *error = nil;
    if (!_audioRecorder) {
        _audioRecorder = [[AVAudioRecorder alloc]initWithURL:urlPath settings:settings error:&error];
        _audioRecorder.delegate = self;
    }
    if ([_audioRecorder prepareToRecord] == YES){
        
    }else {
        int errorCode = CFSwapInt32HostToBig ((int)[error code]);
        NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
    }
    
}
#pragma mark - AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    if (flag) {
        [_audioSession setActive:NO error:nil];
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error
{
    if (error) {
        [_audioSession setActive:NO error:nil];
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    _audioPlayer = nil;
    if (ISIPAD) {
        playerView.playBtn.selected=NO;
    }else{
    _contentBt.selected = NO;
    }
}

#pragma mark - 点击发布按钮
- (void)sendBtn {
    NSLog(@"发布");
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
        //        dispatch_async(dispatch_get_main_queue(), ^{
        
        [[UserManager standerDefult]transformCAFToMP3WithPath:MusicCachesDirectory withNormalName:MUSIC_PRIVATE_NAME withFileName:self.titleString WithComplate:^{
            
            if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isBackPlay) {
                [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
                [[UserManager standerDefult].mainPlayer play];
            }
            
            NSDictionary *dataDic = @{@"PicPath":@"",@"AudioName":@""};
            NSString *mp3FilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",MUSIC_PRIVATE_NAME]];
            MBSendShowController *sendShowVC = [[MBSendShowController alloc] init];
            sendShowVC.dataDic = dataDic;
            sendShowVC.recordPath = mp3FilePath;
            sendShowVC.isFormFreedom = YES;
            sendShowVC.activityId = (_activityId.length > 0 ? _activityId : @"0");
            [self.navigationController pushViewController:sendShowVC animated:YES];
            
        } withFaild:^{
            
        }];
        //        });
    }
}

- (void)setBackItem
{
//    if (ISIPAD) {
//        
//        
//        [self setTitleView:@"录制亲子秀"];
//         self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(onBack)];
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage  imageNamed:@"wenhao"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(help)];
//      
//        return;
//    }
    
    UIImage *img = [UIImage imageNamed:@"fanhui2"];
    UIImage * img1=[UIImage imageNamed:@"fanhui"];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(10, 20+(44-img.size.height)/2., 80, img.size.height);
    [back setImage:img forState:UIControlStateNormal];
    [back setImage:img forState:UIControlStateHighlighted];
    if (ISIPAD) {
        [back setImage:img1 forState:UIControlStateNormal];
        [back setImage:img1 forState:UIControlStateHighlighted];
    }
    [back setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80-img.size.width)];
    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
    
    UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 27, SCREEN_WIDTH, 30)];
    titleLb.text = @"录制亲子秀";
    titleLb.textAlignment = NSTextAlignmentCenter;
    titleLb.textColor = [UIColor blackColor];
    if (ISIPAD) {
         titleLb.textColor = [UIColor whiteColor];
    }
    [self.view addSubview:titleLb];
    
        UIButton *sendQZShowBt = [UIButton buttonWithType:UIButtonTypeCustom];
        sendQZShowBt.frame = CGRectMake(SCREEN_WIDTH-85, titleLb.top, 80, 30);
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao2"] forState:UIControlStateNormal];
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao2"] forState:UIControlStateHighlighted];
    if (ISIPAD) {
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao"] forState:UIControlStateNormal];
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao"] forState:UIControlStateHighlighted];
    }
        sendQZShowBt.backgroundColor = [UIColor clearColor];
        [sendQZShowBt setImageEdgeInsets:UIEdgeInsetsMake(0, 40, 0, 0)];
        [sendQZShowBt addTarget:self action:@selector(help) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:sendQZShowBt];
    
}

#pragma mark - Actions
- (void)onBack
{
    
    //对录制文件删除
    if (_audioRecorder) {
        [_audioRecorder stop];
        _audioRecorder = nil;
    }
    if (_audioSession) {
        [_audioSession setActive:NO error:nil];
        if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isBackPlay) {
            [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[UserManager standerDefult].mainPlayer play];
        }
        _audioSession = nil;
    }
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
        [fileManager removeItemAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME) error:nil];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
//点击帮助
- (void)help {
    MBPlayShowController *playShowVC = [[MBPlayShowController alloc] init];
    [self.navigationController pushViewController:playShowVC animated:YES];
}

@end

    

    
